package com.glasses.business.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.glasses.business.R;
import com.glasses.business.activity.WebDetailActiviy;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.entity.Version;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.AllCacheUtil;
import com.glasses.business.utils.DownloadAppService;
import com.glasses.business.utils.Tools;

import net.neiquan.applibrary.wight.AlertDialog;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ServiceUtils;
import org.haitao.common.utils.ToastUtil;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/7
 * Version：1.0
 */

public class SettingFragment extends AppBaseFragment {
    @InjectView(R.id.setClearCace)
    RelativeLayout setClearCace;
    @InjectView(R.id.setUpdate)
    RelativeLayout setUpdate;
    @InjectView(R.id.setAboutUs)
    RelativeLayout setAboutUs;
    @InjectView(R.id.setLoginOut)
    TextView setLoginOut;
    @InjectView(R.id.cacheTv)
    TextView mCacheSizeTv;
    private AlertDialog dialog1;

    @Override
    public int getRootViewId() {
        return R.layout.fragment_setting;
    }

    @Override
    public void setViews() {
        setTitleTv("设置");
    }

    @Override
    public void initData() {
        try {
            String totalCacheSize = AllCacheUtil.getTotalCacheSize(getActivity().getApplicationContext());
            if (!TextUtils.isEmpty(totalCacheSize)) {
                mCacheSizeTv.setText(totalCacheSize);
            } else {
                mCacheSizeTv.setText("0.0M");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }

    @OnClick({R.id.setClearCace, R.id.setUpdate, R.id.setAboutUs, R.id.setLoginOut})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setClearCace:
                AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity()).setTitle("温馨提示").setMessage("确定清除缓存？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                AllCacheUtil.clearAllCache(getActivity().getApplicationContext());
                                try {
                                    String totalCacheSize = AllCacheUtil.getTotalCacheSize(getActivity().getApplicationContext());
                                    if (!TextUtils.isEmpty(totalCacheSize)) {
                                        mCacheSizeTv.setText(totalCacheSize);
                                    } else {
                                        mCacheSizeTv.setText("0.0M");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialog1.dismiss();
                            }
                        });
                dialog1 = builder1.create();
                dialog1.show();
                break;
            case R.id.setUpdate:
                chickVersion();
                break;
            case R.id.setAboutUs:
                Tools.showDialog(getActivity());
                NetUtils.getInstance().systemContent(1, new NetCallBack() {
                    @Override
                    public void onSuccess(String response, String mssage, ResultModel model) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "关于我们");
                        bundle.putString("url", response);
                        Intent intent = new Intent(getActivity(), WebDetailActiviy.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(boolean dataError, int errorCode, String mssage) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                    }
                }, null);
//                open(new AboutUsFragment());
                break;
            case R.id.setLoginOut:
                MyApplication.getInstance().saveUser(null);
                EventBus.getDefault().post(new BussEvent(BussEvent.Login_Out));
                MyApplication.getInstance().manager.onBackPressed();
                break;
        }
    }

    private int versionCode;

    private void chickVersion() {
        PackageManager packageManager = getActivity().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), PackageManager.GET_ACTIVITIES);
            versionCode = packageInfo.versionCode;
            AppLog.e("versionCode", versionCode + "");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        // 检查版本
        NetUtils.getInstance().updateVersion(new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                final Version version = model.getModel();
                int updateVersionCode = version.getVersionCode();
                AppLog.i("updateVersionCode", updateVersionCode + ".......//");
                if (versionCode < updateVersionCode) {
                    if (ServiceUtils.isServiceRunning(getActivity(), DownloadAppService.serviceName)) {
                        ToastUtil.shortShowToast("升级服务已经启动,无需再次启动");
                    } else {
                        String tishi = getResources().getString(R.string.prompt);

                        AlertDialog.Builder buile = new AlertDialog.Builder(getActivity()).setTitle(tishi).setMessage("检查到版本更新").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                Intent it = new Intent(getActivity(), DownloadAppService.class);
                                it.putExtra(DownloadAppService.SERVICRINTENTURL, version.getDownloadUrl());
                                it.putExtra(DownloadAppService.SERVACESHARENAME, 0);
                                getActivity().startService(it);
                                AppLog.e("启动服务。。。。。。。。。。。。。。");
                            }
                        }).setNegativeButton("取消", null);
                        Dialog dialog = buile.create();
                        if (!dialog.isShowing()) {
                            dialog.show();
                        }
                    }
                }else{
                    ToastUtil.shortShowToast("当前无可更新版本...");
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {

            }
        }, Version.class);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
